package com.example.wificov;


import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.database.myDBHelper;
import com.example.wificovv2.R;
import android.view.MotionEvent;

public class Loadpicture extends Activity {
	//khoi tao database
		myDBHelper db;
		
		//cac bien duoc dung
		int index=0;	
		Resources res;
		Bitmap bm;	
		BitmapDrawable bd;	
		Bitmap mutableBitmap;
		Canvas c;
		Paint p ;
		int imgwidth, imgheight;
		private ArrayAdapter<String> mainAdapter = null;		
		ArrayList<String>array = new ArrayList<String>();
		
		ImageView picture;
		Button loadpicture, savemap, saveAp, marker, getnext;
		EditText width, height, filepicname;
		EditText xAP,yAP, accesspoint;
		ListView listAp = null;
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_loadpicture);		
			
			db = new myDBHelper( this );
			
			// cac doi tuong trong layout
			loadpicture = (Button) findViewById(R.id.loadpicture);			
			savemap = (Button) findViewById(R.id.savemap);
			saveAp = (Button) findViewById(R.id.saveAp);
			marker = (Button) findViewById(R.id.makerAP);
			getnext = (Button) findViewById(R.id.getnext);
			
			width = (EditText) findViewById(R.id.width);
			height = (EditText) findViewById(R.id.height);
			filepicname = (EditText) findViewById(R.id.filepicname);			
			xAP = (EditText) findViewById(R.id.xAp);
			yAP = (EditText) findViewById(R.id.yAp);
			accesspoint = (EditText) findViewById(R.id.accesspoint);
			listAp = (ListView) findViewById(R.id.listAp);			
			mainAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);	
			listAp.setAdapter(mainAdapter);
			picture = (ImageView) findViewById(R.id.picture);
			
			// Khởi tạo đối tượng vẽ ảnh lên ImageView
			p = new Paint();
			p.setAntiAlias(true);
			p.setColor(Color.YELLOW);	
			
			// Lay picture tu thu vien anh cua res dua vao View
			loadpicture.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					//Chuyển tới đường dẫn chứa file picture cần load
//					String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
//					File imgFile = new  File(“/sdcard/Images/test_image.jpg”);
//
//					File imgFile = new File(path);
//					if(imgFile.exists())
//					{
//					   Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//					   ImageView imageView=(ImageView)findViewById(R.id.imageView);
//					  imageView.setImageBitmap(myBitmap);
//					}
					
					index =0;				
				    res = getResources();				    
				    //Get image's size
				    BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
				    dimensions.inJustDecodeBounds = true;
				    //Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.newmap, dimensions);
				    imgheight = dimensions.outHeight;
				    imgwidth =  dimensions.outWidth;
				    //cast from immutableBitmap to mutableBitmap to insert into Canvas 
				    Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.newmap );
				    mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);			
				    c = new Canvas( mutableBitmap ); 
				    //fit imageview with image loaded
				    picture.getLayoutParams().width = c.getWidth();
				    picture.getLayoutParams().height = c.getHeight();				   
				    picture.setImageBitmap( mutableBitmap );				    
				}});
			
			// Lưu kích thước tỷ lệ của picture
			savemap.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
						//luu toa do va kich thuoc picture da load
						db.addMapInfor(filepicname.getText().toString(),0f, 0f, 
								Float.parseFloat(width.getText().toString()), 
								Float.parseFloat(height.getText().toString()));	
			}});
			
			// set xAP and yAP
			picture.setOnTouchListener(new View.OnTouchListener()
			{
				 public boolean onTouch(View v,  MotionEvent event) {
				       // if(event.getAction() == MotionEvent.ACTION_UP) {
					 	int screenX = (int)event.getRawX();
		                int screenY = (int) event.getRawY();	                
		                
		                int[] posXY = new int[2];
		                v.getLocationOnScreen(posXY);
		                int x = posXY[0];
		                int y = posXY[1];
		                
		                int viewX = screenX - x;
		                int viewY = screenY - y;
				            
			            xAP.setText(Float.toString(viewX));
			            yAP.setText(Float.toString(viewY));
			            
			            Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.newmap );
					    mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);
					    c = new Canvas( mutableBitmap );
					    c.drawCircle(viewX, viewY , 3, p);
			            picture.setImageBitmap( mutableBitmap );
			            					
				        return true;				            				      
				    }}); 
			// Đánh dấu vị trí được chọn
			marker.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					//Add tên AP vào listview
					String name = accesspoint.getText().toString();
					//Đưa vào danh sách
					array.add(name);
					//cập nhật giao diện
					mainAdapter.notifyDataSetChanged();									
					
					//Đánh dấu vị trí các AP trên picture
					float x;
				    float y;
					x = Float.parseFloat(xAP.getText().toString());
				    y = Float.parseFloat(yAP.getText().toString());
				    //calculate the ratios between image's size and screen size
				    Paint p = new Paint();
				    p.setAntiAlias(true);
					p.setColor(Color.YELLOW);
					Canvas cv = new Canvas(mutableBitmap);
					cv.drawCircle(x,y, 2, p);
					picture.setImageBitmap(mutableBitmap);	
			}});
			
			//Lưu toạ độ và tên của các AP
			saveAp.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					String MapName = filepicname.getText().toString();					
					int mapId = db.getMapId(MapName);
					db.addAPLocation(mapId, accesspoint.getText().toString(), 
							Float.parseFloat(xAP.getText().toString()), 
							Float.parseFloat(yAP.getText().toString()));
					//Sau khi update thì xóa trắng dữ liệu 
					 accesspoint.setText("");
					 accesspoint.requestFocus();
			}});
			
			// Chon nut nay de chuyen sang Activity Innitialvalue
			getnext.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					if( width.getText().toString().equals("") || height.getText().toString().equals("") )
						Toast.makeText( Loadpicture.this, "Nhap day du chieu dai va chieu rong thuc dia", Toast.LENGTH_SHORT).show();
					else{
						Intent intent = new Intent(Loadpicture.this, Innitialvaluepic.class);
						int mapId = db.getMapId(filepicname.getText().toString());
						intent.putExtra("mapid", mapId);
						startActivity(intent);
					}
				}
			});
			 
		}	
}
